package com.ctgu.demo.controller;

import com.alibaba.druid.util.StringUtils;
import com.ctgu.demo.entity.User;
import com.ctgu.demo.error.EmBusinessError;
import com.ctgu.demo.error.exception.BusinessException;
import com.ctgu.demo.error.response.CommonReturnType;
import com.ctgu.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import static com.ctgu.demo.controller.BaseController.CONTENT_TYPE_FORMED;

/**
 * @program: MybitsPlusConfig
 * @description:
 * @author: gh
 * @create: 2020-06-22 12:24
 **/
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @RequestMapping(value = "/register",method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORMED})
    public CommonReturnType register(@RequestParam(name = "telephone") String userTelephone,
                                     @RequestParam(name = "otpCode") String otpCode,
                                     @RequestParam(name = "username")String userNickName,
                                     @RequestParam(name = "password")String password,
                                     @RequestParam(name = "birthday")Date birthday,
                                     @RequestParam(name = "address") String location,
                                     @RequestParam(name = "sex")String sexual) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        //验证用户手机号和otpCode是否匹配
        String inSessionOtpCode = (String)this.httpServletRequest.getSession().getAttribute(userTelephone);
        if (!com.alibaba.druid.util.StringUtils.equals(otpCode, inSessionOtpCode)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "短信验证码错误");
        }
        //用户的注册流程
        User user = new User();
        user.setUserNickname(userNickName);
        user.setUserTelephone(userTelephone);
        user.setUserPassword(this.encodeByMd5(password));
//        Date date = DateUtils.stringToShortDate(birthday);
        user.setBirthday(birthday);
        user.setLocation(location);
        user.setSexual(sexual);

        userService.register(user);
        return CommonReturnType.create(null);
    }

    public String encodeByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //提供信息摘要算法
        MessageDigest md5 = MessageDigest.getInstance("MD5");

        //使用BASE64Encoder实现64种字元组合成加密密码
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String newstr = base64Encoder.encode(md5.digest(str.getBytes("utf-8")));
        return newstr;
    }

    @InitBinder
    //为UserController注册一个绑定器初始化方法
    public void initBinder(WebDataBinder binder, WebRequest request) {

        //转换日期
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        // CustomDateEditor为自定义日期编辑器
    }

    //用户获取otp短信接口
    @RequestMapping("/getOtp")
    public CommonReturnType getOtp(@RequestParam(name="telephone")String telephone){

        //按一定规则生成OTP验证码
        Random random = new Random();
        int randomInt = random.nextInt(899999);
        randomInt += 100000;
        String otpCode = String.valueOf(randomInt);

        //将OTP验证码同对应用户的telephone关联，未使用redis
        httpServletRequest.getSession().setAttribute(telephone,otpCode);

        //将OTP验证码通过短信通道发送给用户,暂时未处理
        System.out.println("telephone = " + telephone + " otpCode = "
                + otpCode);
        return CommonReturnType.create(null);
    }
    @RequestMapping(value = "/login",method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORMED})
    public CommonReturnType login(@RequestParam(name = "telephone")String userTelephone,
                                  @RequestParam(name = "password")String password) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        //入参校验
        if (org.apache.commons.lang3.StringUtils.isEmpty(userTelephone) ||
                StringUtils.isEmpty(password)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        //校验登陆是否合法
        User user = userService.validateLogin(userTelephone,this.encodeByMd5(password));

        //将登陆凭证加入到用户登陆成功的session内
        this.httpServletRequest.getSession().setAttribute("IS_LOGIN",true);
        this.httpServletRequest.getSession().setAttribute("LOGIN_USER",user);
        return CommonReturnType.create(null);


    }
}
